<template>
  <div class="chatclient-wrap">
    <div class="header">
      <!-- 在头部显示应用的名称和logo -->
      <div class="left-logo">
        <!-- 图标的大小通过fontSize调整，设置宽度和高度无效 -->
        <!-- <RobotOutlined :style="{ height: '32px', width: '32px' }" /> -->
        <CommentOutlined :style="{ fontSize: '28px' }" />
        <!-- <img class="robot-avatar" :src="robotAvatar" /> -->
      </div>
      <div class="left-title">
        <div class="main-title">DeepSeek AI 知识库智能助手 </div>
        <div class="sub-title">{{ robotName }}</div>
      </div>
    </div>
    <div id="lke-client-chat" class="body">
      <!-- 显示对话的内容 -->
      <!-- <v-popper ref="first" clazz="pop-demo" :use-arrow="true">
                  <div class="pop-demo-list" v-for="pop in popperList" :key="pop.id">
                    <v-button type="link" kind="primary" @click="openSearchUrl(pop, pop.id)">
                      {{ pop.id }}.{{ pop.name }}
                      <v-icon remote name="arrow_right_line" size="12" valign="-1"></v-icon>
                    </v-button>
                  </div>
                </v-popper> -->
      <div class="qa-item" v-for="(item, index) in msgList" :key="index">
        <!-- 时间戳 -->
        <div
          class="timestamp"
          v-if="
            index === 0 ||
            (index !== 0 &&
              item.timestamp &&
              Number(item.timestamp) - Number(msgList[index - 1].timestamp) > timestampGap)
          "
        >
          {{ item.tmstr }}
        </div>

        <!-- 问题 -->
        <div class="question-item" v-if="item.is_from_self">
          <!-- 指示问题的状态是否为正在加载中 -->
          <a-spin class="qs-loading" v-if="item.is_loading" />
          <!-- 显示问题的内容；使用markdown显示 -->
          <span class="question-text">{{ item.content }}</span>
          <!-- 头像 -->
          <div class="question-avatar">
            <!-- <img :class="`${prefixCls}__header`" :src="getUserInfo.avatar" /> -->
            <img class="user-avatar" :src="getUserInfo.avatar" />
          </div>
          <!-- <VueMarkdown
                      class="question-text"
                      style="max-width: 352px"
                      :source="item.content"
                      :anchorAttributes="{ target: '_blank' }"
                      :linkify="false"
                    /> -->
        </div>
        <!-- 答案 -->
        <div class="answer-item" v-if="!item.is_from_self">
          <!-- 头像 -->
          <div class="contacter-avatar">
            <img class="robot-avatar" :src="item.from_avatar" />
          </div>

          <!-- 答案信息 -->
          <div class="answer-info" :ref="item.record_id">
            <div
              v-if="
                item.agent_thought &&
                item.agent_thought.procedures &&
                item.agent_thought.procedures.length > 0
              "
            >
              <!-- 思考部分   -->
              <MsgThought
                v-for="(thought, index) in item.agent_thought.procedures"
                :key="index"
                :content="thought.debugging.content"
                :title="thought.title"
                :titleIcon="thought.icon"
                :nodeName="thought.name"
                :status="thought.status"
                :elapsed="thought.elapsed"
                :detailVisible="thought.detailVisible"
              />
            </div>
            <div class="loading" v-if="item.loading_message">正在思考中</div>
            <!-- 回复主体 -->
            <MsgContent
              :showTags="true"
              :recordId="item.record_id"
              :isReplaceLinks="true"
              :loadingMessage="item.loading_message"
              :content="item.content"
              :isFinal="item.is_final"
              :isMdExpand="item.isMdExpand"
            />
            <!-- @littleTagClick="littleTagClick" -->
            <!-- 参考来源 -->
            <!-- <Reference
            v-if="item.references && item.references.length > 0"
            :references-list="item.references"
          /> -->
            <!-- 运行状态 -->
            <!-- <TokensBoardBfr
            class="tokens-board-class"
            :showDtl="true"
            :tokensData="item.tokens_msg"
          ></TokensBoardBfr> -->
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="question-input">
        <!-- 固定在底部显示对话输入框 -->
        <!-- 停止生成 -->
        <div class="stop-button" v-if="isGeneratingReply">
          <a-button @click="onStopStream"><StopOutlined />停止生成</a-button>
        </div>
        <div v-if="disableInput" class="question-mask"></div>
        <div
          :class="[
            'question-input-inner',
            { inputFocus: inputFocus, disabled: isGeneratingReply || isThinking },
          ]"
        >
          <a-textarea
            v-model:value="inputQuestionContent"
            :placeholder="
              disableInput
                ? '请等待与AI服务端建立连接。'
                : '与AI服务端连接成功。请在此输入问题，按Ctrl+Enter或点击右侧的发送按钮发送您的提问。'
            "
            :disabled="disableInput || isGeneratingReply || isThinking"
            :auto-size="{ minRows: 5, maxRows: 10 }"
            class="question-input-inner__textarea"
            @change="updateFocus(true)"
            @pressEnter="onPressEnter"
          />
          <div class="question-input-inner__toolbar">
            <div class="toolbar-left"></div>
            <div class="toolbar-right">
              <div :class="['send-icon', { disabled: isSendIconDisabled || disableInput }]">
                <Tooltip placement="top" title="发送">
                  <a-button
                    shape="circle"
                    :type="isSendIconDisabled === false ? 'primary' : 'default'"
                    @click="onSendQuestion"
                  >
                    <SendOutlined /> </a-button
                ></Tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import {
    defineComponent,
    ref,
    unref,
    reactive,
    provide,
    computed,
    nextTick,
    onBeforeMount,
    onMounted,
    onUnmounted,
    watch,
  } from 'vue';

  import { Tooltip } from 'ant-design-vue';
  import {
    RobotOutlined,
    CommentOutlined,
    StopOutlined,
    SendOutlined,
  } from '@ant-design/icons-vue';

  import moment from 'moment';
  import { buildUUID } from '/@/utils/uuid';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useUserStore } from '/@/store/modules/user';
  import { getFileApi } from '/@/api/platform/file';
  import headerImg from '/images/header.jpg';

  import { useMessage } from '/@/hooks/web/useMessage';
  const { createErrorModal, createMessage, notification } = useMessage();

  //腾讯云API模型及接口
  import { TencentCloudApiWSTokenResponseDto } from '/@/api/demo/model/tencentCloudModel';
  import { getWSToken } from '/@/api/demo/tencentcloud';

  import axios from 'axios';
  import { WebSocketClient } from '/@/utils/websocket';

  import { MsgContent, MsgThought } from 'lke-component-vue3';
  import 'lke-component-vue3/style.css';

  export default defineComponent({
    name: 'TencentLKEChatClient',
    components: {
      Tooltip,
      RobotOutlined,
      CommentOutlined,
      StopOutlined,
      SendOutlined,
      MsgContent,
      MsgThought,
    },
    setup() {
      console.log('TencentLKEChatClient setup');

      const { prefixCls } = useDesign('header-user-dropdown');
      const { t } = useI18n();
      const userStore = useUserStore();
      const { globalProjectCode } = useGlobSetting();
      const { uploadUrl } = useGlobSetting();
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getFileApi);
      const getUserInfo = computed(() => {
        const { realName = '', avatar, desc } = userStore.getUserInfo || {};
        return {
          realName,
          avatar: avatar ? getImageFileUrlPrefix.value + avatar : headerImg,
          desc,
        };
      });

      //腾讯云API接口调用使用的token，如果为空表示未进行获取
      let token = null;
      //WebSocket客户端
      let wsClient: WebSocketClient = null;

      const robotName = ref<String>();
      const robotAvatar = ref<String>();

      const timestampGap = ref<number>(5 * 60); // 两次问题间隔大于5min，则展示时间戳（接口侧返回的时间戳是秒级）
      const isSendIconDisabled = ref<boolean>(true);
      //提问输入框中输入的问题
      const inputQuestionContent = ref<String>();
      const inputFocus = ref<boolean>(false);
      const disableInput = ref<boolean>(true); //是否禁止输入；默认在没有建立WebSocket时不能输入问题
      const isGeneratingReply = ref<boolean>(false); // 是否生成回答中
      const isThinking = ref<boolean>(false); // 是否思考中

      //问答的列表，包含
      const msgList = ref([]);
      //问答的request_id和消息index的map关系，方便进行消息的替换和删除
      const msgRequestIdAndIndexMap = new Map();

      //调用腾讯接口获取token
      function getToken() {
        getWSToken().then((res) => {
          console.log('getWSToken res', res);
          //判断token必须要有，并且余额大于0才有效
          if (!res) {
            //返回对象为空
            createErrorModal({
              title: t('sys.api.errorTip'),
              content: '调用腾讯云API接口获取token错误，返回对象为空',
              getContainer: () => document.body,
            });
          } else {
            if (!res.token) {
              //返回结果中token为空
              createErrorModal({
                title: t('sys.api.errorTip'),
                content: '调用腾讯云API接口获取token错误，返回结果中token为空',
                getContainer: () => document.body,
              });
            } else {
              if (res.balance <= 0) {
                //余额大于0才有效
                createErrorModal({
                  title: t('sys.api.errorTip'),
                  content: '调用腾讯云API接口获取token错误，返回结果中余额不大于0',
                  getContainer: () => document.body,
                });
              } else {
                //余额大于0才有效
                token = res.token;
                //在token有效时才进行WebSocket的连接
                initWebSocket();
              }
            }
          }
        });
      }

      function initWebSocket() {
        // 创建客户端实例
        try {
          wsClient = new WebSocketClient({
            url: 'wss://wss.lke.cloud.tencent.com/v1/qbot/chat/conn/?EIO=4&transport=websocket',
            onOpen: () => {
              console.log('连接成功！');
              //连接成功后设置提问输入框禁用状态为false
              disableInput.value = false;
            },
            onError: () => {
              console.log('连接异常:');
              //连接异常后设置提问输入框禁用状态为true
              disableInput.value = true;
            },
            onMessage: (data) => onWebSocketReceiveMessage(data),
          });
        } catch (e) {
          console.log(e, 'eeee');
          //连接异常后设置提问输入框禁用状态为true
          disableInput.value = true;
        }
      }

      //接收到websocket消息处理
      function onWebSocketReceiveMessage(receiveData) {
        console.log('onWebSocketReceiveMessage receiveData', receiveData);
        //心跳包内容为2，需要响应内容为3；否则websocket会断开
        if (receiveData) {
          //根据data中的起始字符进行判断消息的类型：建立连接-0、心跳包-2、
          let firstChar = receiveData.substring(0, 1);
          if (firstChar === 2 || firstChar === '2') {
            console.log('onWebSocketReceiveMessage 判定收到数据为心跳包，回复3');
            //判定为心跳包，进行回复
            sendDataToWebSocketServer(3);
          } else if (firstChar === 0 || firstChar === '0') {
            //0{"sid":"d19qkaumvddcdgo8e2kg","upgrades":[],"pingInterval":25000,"pingTimeout":5000}
            console.log(
              'onWebSocketReceiveMessage 判定收到数据为建立连接成功后的服务器回包，发送token鉴权',
            );
            //格式如：40{"token":"xx-xx-xx-xx-xx"}
            //判断如果token为空时不进行发送，先调用获取token得到token后再进行连接超过
            if (!token) {
              createErrorModal({
                title: t('sys.api.errorTip'),
                content: '对话连接打开时，由于token为空暂时无法进行对话',
                getContainer: () => document.body,
              });
            } else {
              let sendData = {
                token: token,
              };
              sendDataToWebSocketServer(40, sendData);
            }
          } else {
            //40{"sid":"d19qkaumvddcdgo8e2l0"}
            if (receiveData.length >= 0x2) {
              //长度超过2个字符
              let first2Char = receiveData.substring(0, 2);
              if (first2Char === 40 || first2Char === '40') {
                //回复发送的40鉴权消息
                console.log('onWebSocketReceiveMessage 判定收到数据为发送token鉴权的回复消息');
              } else if (first2Char === 41 || first2Char === '41') {
                //关闭连接
                console.log(
                  'onWebSocketReceiveMessage 判定收到数据为关闭连接，对WebSocket连接进行关闭',
                );
                wsClient.close();
              } else if (first2Char === 42 || first2Char === '42') {
                //42表示服务端返回的消息，需要根据type来区分是哪种消息（可能是错误提示、回复等）
                //427777844["error",{"type":"error","error":{"code":460001,"message":"Token 校验失败"}}]
                //427720526["error",{"type":"error","error":{"code":460001,"message":"Token 校验失败"}}]
                //427792789["error",{"type":"error","error":{"code":460001,"message":"Token 校验失败"}}]
                //427918037["reply",{"type":"reply","payload":{"can_feedback":false,"can_rating":false,"content":
                //427918068["token_stat",{"type":"token_stat","payload":{"elapsed":1064,"free_count":0,"order_
                //427918090["reply",{"type":"reply","payload":{"can_feedback":false,"can_rating":true,"content":"
                //错误信息：获取第一个中括号开始之后的进行json解析
                console.log('onWebSocketReceiveMessage 判定收到数据为服务端回复信息');
                console.log('onWebSocketReceiveMessage 判定收到数据为错误提示信息');
                let jsonStartIndex = receiveData.indexOf('[');
                if (jsonStartIndex > 0x0) {
                  let jsonStr = receiveData.substring(jsonStartIndex);
                  let jsonObj = JSON.parse(jsonStr);
                  if (!jsonObj) {
                    console.log(
                      'onWebSocketReceiveMessage 判定收到数据为服务端回复信息，转换为json的对象为空',
                    );
                  } else if (Array.isArray(jsonObj)) {
                    //根据json数组的第1个元素中的字符串判断或者根据json数组中第2个元素中的type进行判断消息类型
                    if (
                      jsonObj[0x0] === 'error' ||
                      (jsonObj.length > 0x1 && jsonObj[0x1].hasOwnProperty('error'))
                    ) {
                      //判定为返回信息时错误提示信息
                      let errorJsonObj = jsonObj[0x1]['error']; //获取json对象中的error属性值
                      const { code, message } = errorJsonObj;
                      console.log(
                        'onWebSocketReceiveMessage 错误代码=' + code + ' 错误信息=' + message,
                      );
                    } else if (jsonObj[0x0] === 'token_stat') {
                      //服务端响应后会返回token用量和详情
                      console.log(
                        'onWebSocketReceiveMessage 消息类型为回复类型-token_stat，消息内容',
                        jsonObj,
                      );
                      //此时标识为正在思考状态
                      isThinking.value = true;
                    } else if (jsonObj[0x0] === 'reply') {
                      console.log(
                        'onWebSocketReceiveMessage 消息类型为回复类型-replay，消息内容',
                        jsonObj,
                      );
                      //回复信息：对话的回复信息
                      //其他类型信息：获取type和payload
                      let infoJsonObj = jsonObj[0x1];
                      const { message_id, payload } = infoJsonObj;
                      const replayPayload = payload; //payload的属性与显示消息所需的属性一致
                      //获取payload中的显示到标题中的机器人名称中，也可以同时获取logo
                      robotName.value = payload.from_name;
                      robotAvatar.value = payload.from_avatar;
                      // 回复消息是否结束等状态可以根据下面的属性进行判断
                      // is_evil--是否命中敏感内容、
                      // is_final--消息是否已输出完成
                      // is_from_self--消息是否由客户端发出
                      // is_llm_generated--是否为模型生成内容
                      //问答发送的消息也需要单独作为1条msg进行显示，通过reply响应的is_from_self为true判定为是问答发送的消息
                      //发送的消息的request_id需要与回复的消息的request_id分开，使用同一个request_id会导致2条消息作为同一条消息无法分开显示
                      //获取消息中的request_id，如果在已有的msgList中有相同的request_id进行替换已有信息
                      let request_id = replayPayload.request_id;
                      //如果当前消息判定为是发送的消息，在request_id前面增加send标识
                      if (replayPayload.is_from_self === true) {
                        //消息是否由客户端发出，本次收到的回复信息是服务端的收到回执信息
                        request_id = 'send' + replayPayload.request_id;
                        console.log(
                          'onWebSocketReceiveMessage 消息由客户端发出，本次收到的回复信息是服务端的收到回执信息',
                        );
                        //此时标识为正在思考状态
                        isThinking.value = true;
                      } else {
                        //如果不是客户端发送的消息，则为服务端回复的消息，设置思考状态为false
                        isThinking.value = false;
                        //判断消息是否已输出完成，设置是否在生成回复信息状态
                        if (replayPayload.is_final === true) isGeneratingReply.value = false;
                        else isGeneratingReply.value = true;
                      }

                      //设置时间格式化，根据回复中的timestamp格式化输出最终显示在界面中的时间
                      if (replayPayload && replayPayload.timestamp)
                        replayPayload.tmstr = moment(
                          new Date(
                            String(replayPayload.timestamp).length === 10
                              ? replayPayload.timestamp * 1000
                              : Number(replayPayload.timestamp),
                          ),
                        ).format('MM-DD HH:mm');

                      //根据request_id替换或添加到消息队列中
                      if (msgRequestIdAndIndexMap.has(request_id)) {
                        //相同的request_id已经存在，进行更新替换
                        let msgIndex = msgRequestIdAndIndexMap.get(request_id);
                        if (msgIndex >= 0x0) {
                          msgList.value[msgIndex] = replayPayload;
                        }
                      } else {
                        //不存在该request_id，进行添加
                        msgList.value.push(replayPayload);
                        msgRequestIdAndIndexMap.set(request_id, msgRequestIdAndIndexMap.size);
                      }
                    } else {
                      //其他类型信息：获取type和payload
                      let infoJsonObj = jsonObj[0x1];
                      const { type, payload } = infoJsonObj;
                      console.log(
                        'onWebSocketReceiveMessage 消息类型=' + type + ' 消息内容=' + payload,
                      );
                    }
                  } else {
                    console.log(
                      'onWebSocketReceiveMessage 判定收到数据为服务端回复信息，json的对象不为空并且不是数组，暂时无法进行处理',
                    );
                  }
                }
              } else {
                console.log('onWebSocketReceiveMessage 无法判定服务端回复的消息类型');
              }
            }
          }
        }
      }

      //向WebSocket发送消息
      function sendDataToWebSocketServer(msgType: Number | any, data = null) {
        if (!data) {
          //如果数据为空，表示只发送消息类型
          wsClient.send(msgType);
        } else {
          //格式如：40{"token":"xx-xx-xx-xx-xx"}
          wsClient.send(msgType + JSON.stringify(data));
        }
      }

      function updateFocus(isFocus) {
        // console.log('updateFocus', isFocus);
        inputFocus.value = isFocus;
      }
      // 回车键
      function onPressEnter(event) {
        console.log('QuestionInput onPressEnter', event);
        //判断回车时是要发送消息还是换行；默认只按enter是换行
        if (event.keyCode === 13) {
          if (
            event.metaKey === true ||
            event.altKey === true ||
            event.shiftKey === true ||
            event.ctrlKey === true
          ) {
            //判断按下enter的同时是否有按ctrl、alt、shift、meta键，如果有任意1个都当做是换行
            event.preventDefault();
            onSendQuestion();
          } else {
            event.preventDefault();
            inputQuestionContent.value = inputQuestionContent.value + '\n';
          }
        }
      }

      // 发送问题
      function onSendQuestion() {
        console.log('QuestionInput onSendQuestion');
        if (disableInput.value) return;
        if (!inputQuestionContent.value.trim()) {
          return;
        }
        //对话接口文档：https://cloud.tencent.com/document/product/1759/105560#d713b5ec-c000-4d8f-80f3-e145190b81d9
        //格式如：42["send",{"payload":{请参考下面各个不同事件的数据结构}}]
        //每次请求由发送端生成1个request_id和session_id；后面根据收到的回复信息中的request_id进行问题对应
        let request_id = buildUUID();
        let sendData = [
          'send',
          {
            payload: {
              request_id: request_id,
              session_id: request_id, //session_id保持与request_id相同
              content: escapeUserInput(inputQuestionContent.value),
            },
          },
        ];
        sendDataToWebSocketServer(42, sendData);
        //发送问题后清空问题文字
        inputQuestionContent.value = '';

        // 问题发出后，对话框立即滚动至底部
        // 回调函数形式
        nextTick(() => {
          // const sDom = document.querySelector('.client-chat');
          const sDom = document.querySelector('#lke-client-chat'); //按ID选择对话框DOM
          console.log('sDom.scrollTo', sDom);
          if (!sDom) return;
          //滚动到底部
          sDom.scrollTo({
            top: sDom.scrollHeight,
            // behavior: 'smooth'
          });
        });
      }
      // 停止生成
      function onStopStream() {
        console.log('QuestionInput onStopStream');
        //需要调用父组件中的方法停止生成

        isGeneratingReply.value = false;
      }

      function escapeUserInput(input) {
        const parts = input.split(/(<script[^>]*>.*?<\/script>|<[^>]*>)/gi);
        return parts
          .map((part) => {
            if (part.startsWith('<script')) {
              return escapeHtml(part);
            } else if (part.startsWith('<')) {
              return escapeHtml(part);
            } else {
              return part;
            }
          })
          .join('');
      }

      onMounted(() => {
        console.log('TencentLKEChatClient onMounted');
        //在页面加载后调用demo中的接口从腾讯云API获取token，在获取token方法中成功时进行对话WebSocket的连接
        //模拟在页面加载后延迟5秒建立WebSocket连接
        // getToken();
        setTimeout(() => {
          getToken();
        }, 3000);
      });
      return {
        prefixCls,
        getUserInfo,
        getImageFileUrlPrefix,
        robotName,
        robotAvatar,
        msgList,
        isSendIconDisabled,
        timestampGap,
        inputFocus,
        disableInput,
        isGeneratingReply,
        isThinking,
        inputQuestionContent,
        updateFocus,
        onPressEnter,
        onSendQuestion,
        onStopStream,
      };
    },
    watch: {
      //watch中对ref变量赋值要求：前面使用this，不使用.value
      inputQuestionContent: function (newVal, oldVal) {
        console.log('watch inputQuestionContent', newVal);
        if (newVal.trim()) {
          //如果输入的内容不为空发送按钮为可用状态
          this.isSendIconDisabled = false;
        } else {
          this.isSendIconDisabled = true;
        }
      },
    },
  });
</script>
<style lang="less">
  .chatclient-wrap {
    /* 定义变量，需要--开头 */
    --border-normal: 1px;
    --color-primary-normal: #4a70ff;
    --color-text-primary: #00010aed;
    --inverse-opacity-3: hsla(0, 0%, 100%, 0.6);
    --color-text-caption: #010b3269;
    --color-error-normal: #f75559;
    --color-bg-2: #fff;
    --shadow-small-light: #a1abc2;
    --color-border-normal: #11204621;

    position: relative;
    width: 100%;
    // height: 100%;
    //由于drawer组件自动添加了scroll，导致默认的body高度是根据内容自动
    height: calc(100vh - 100px);
    // overflow: hidden;
    display: flex;
    flex-wrap: nowrap; /* 防止换行 */
    flex-direction: column; //按列排列
    // justify-content: center;
    justify-content: space-between; /* 子元素之间有空间，两端对齐 */
    align-items: center;

    .header {
      width: 100%;
      height: 80px;
      //设置header中的dom按行排列
      display: flex;
      flex-direction: row;
      align-items: center;
      overflow-x: hidden;
      // background: linear-gradient(180deg, #eaeef6 0%, #ffffff 100%), #ffffff;
      background: linear-gradient(271.81deg, #305af5 0%, #309cff 52.76%, #00d0e9 100%);
      border-radius: 12px;

      .left-logo {
        // height: 100%;
        // min-width: 40px;
        // width: 40px;
        // min-height: 32px;
        margin-left: 12px;
        margin-right: 12px;
      }

      .left-title {
        display: flex;
        flex-direction: column;

        .main-title {
          font-weight: 500;
          font-size: 16px;
          color: var(--color-text-primary);
        }
        .sub-title {
          font-weight: 400;
          font-size: 12px;
          color: var(--inverse-opacity-3);
          margin-top: -5px;
        }
      }
    }

    .body {
      width: 100%;
      height: calc(100% - 220px); //总高度减去header和footer的高度
      overflow-x: hidden;
      overflow-y: scroll; //对话内容部分设置滚动条
      // background: linear-gradient(180deg, #eaeef6 0%, #ffffff 100%), #ffffff;
      background: rgba(244, 245, 247, 0.9);
      border-radius: 12px;

      .qa-item {
        display: flex;
        flex-direction: column;
        margin-bottom: 16px;
        font-weight: 400;
        font-size: 14px;
        color: var(--color-text-primary);

        .timestamp {
          font-weight: 400;
          font-size: 12px;
          line-height: 16px;
          text-align: center;
          color: var(--color-text-caption);
          margin: 16px 0;
        }

        .question-item {
          display: flex;
          align-items: center;
          width: fit-content;
          text-align: center;
          align-self: flex-end;
          padding-left: 44px; //左边留出显示图片的位置

          .question-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-left: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .qs-error {
            min-width: 16px;
            margin-right: 10px;
            color: var(--color-error-normal);
          }

          .qs-loading {
            margin-right: 10px;
          }

          .question-text {
            background: #6b99e8;
            border-radius: 6px;
            // padding: 0 12px;
            text-align: left;
            word-break: break-all;
            word-wrap: break-word;

            code {
              white-space: break-spaces;
            }

            img {
              max-width: 80%;
            }
          }
        }

        .summary-item {
          align-self: center;
          margin: 12px 0;
        }

        .answer-item {
          display: flex;

          .contacter-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .answer-info {
            position: relative;
            display: flex;
            flex-direction: column;
            padding: 12px;
            background: #1ce9ec;
            border-radius: 6px;
            width: calc(100% - 67px);

            .answer-expand {
              display: flex;
              justify-content: center;
              align-items: center;
              cursor: pointer;
              width: 44px;
              height: 24px;
              margin-bottom: 12px;
              background: var(--color-bg-2);
              box-shadow: var(--shadow-small-light);
              border-radius: 16px;
              align-self: center;
            }

            .stop-ws {
              color: var(--color-text-caption);
              margin-left: 5px;
            }

            .answer-source {
              margin: 12px 0;
              font-size: 14px;
              color: var(--color-text-caption);
              text-align: left;

              .v-button {
                text-decoration: none;
                text-align: left;
              }
            }
          }
        }
      }
    }

    .footer {
      width: 100%;
      height: 135px;
      position: relative;
      overflow: hidden;

      .question-input {
        // position: fixed;
        // width: 100%;
        // margin-top: -110px;
        background: rgba(255, 255, 255, 0.6);
        backdrop-filter: blur(20px);
        border-bottom-left-radius: 12px;
        border-bottom-right-radius: 12px;

        .stop-button {
          display: flex;
          justify-content: center;

          button {
            box-shadow: var(--shadow-small);
            border: none;
            padding: 6px 8px;
          }
        }

        .question-mask {
          width: 100%;
          height: 110px;
          position: absolute;
          z-index: 200;
          background: rgba(255, 255, 255, 0);
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: bolder;
        }

        &-inner {
          display: flex;
          flex-direction: column;
          margin: 12px;
          background-color: rgba(255, 255, 255, 0.8);
          border: var(--border-normal) solid;
          border-color: var(--color-border-normal);
          border-radius: var(--radius-large);

          .v-textarea--default {
            border-radius: var(--radius-large);
          }

          &:has(.question-input-inner),
          &:has(.v-textarea--focus),
          &.inputFocus {
            border-color: var(--color-primary-normal);
          }

          &.disabled {
            background-color: var(--color-fill-disable);
            border-color: var(--color-border-disable) !important;

            .v-textarea__placeholder {
              color: var(--color-text-disable);
            }
          }

          &__textarea {
            width: 100%;
            max-height: 120px;
            border: none;
            background: none;

            .v-textarea__txt {
              overflow-y: overlay;
              font-size: 14px;
              font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue,
                Helvetica, Arial, PingFang SC, Microsoft YaHei, Noto Sans, sans-serif !important;
            }
          }

          .v-textarea--focus {
            border: none;
          }

          &__toolbar {
            //使用绝对定位，显示在最底部
            position: absolute;
            bottom: 0; /* 将子元素底部对齐到父元素底部 */
            right: 10px;
            display: flex;
            justify-content: space-between;
            z-index: 10;
            margin: 8px;

            .v-icon {
              cursor: pointer;
            }

            .toolbar-left {
              display: flex;

              .v-icon {
                &.disabled {
                  cursor: not-allowed;
                  color: var(--color-text-disable);
                }

                padding: 6px;
              }
            }

            .toolbar-right {
              display: flex;
              gap: 4px;

              .stop-icon {
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                padding: 6px;
              }

              .send-icon {
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
              }

              .send-icon {
                color: var(--color-primary-normal);
              }

              .stop-icon:hover,
              .send-icon:hover {
                background: var(--color-fill-hover);
                border-radius: 3px;
              }

              .stop-icon:active,
              .send-icon:active {
                background: var(--color-fill-active);
                border-radius: 3px;
              }

              .stop-icon.disabled,
              .send-icon.disabled {
                background: none;
                cursor: not-allowed;

                .v-icon {
                  cursor: not-allowed;
                  color: var(--color-text-disable);
                }
              }

              .split-line {
                align-self: center;
                width: 1px;
                height: 16px;
                background: var(--color-divider-normal);
                margin: 0 5px;
              }
            }
          }
        }
      }
    }
  }
</style>
